package cn.newgrand.netcall.integration.interaction;

import java.io.IOException;

import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import org.jivesoftware.resource.Default;
import org.jivesoftware.resource.Res;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.util.BrowserLauncher;
import org.jivesoftware.spark.util.StringUtils;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.settings.JiveInfo;

import cn.newgrand.common.NativeTools;
import cn.newgrand.common.StringUtil;
import cn.newgrand.netcall.integration.AppSysRes;
import cn.newgrand.netcall.integration.IntegrationManager;
import cn.newgrand.netcall.integration.setting.SettingPreference;
import cn.newgrand.netcall.integration.setting.SettingPreferences;

import com.jniwrapper.*;
import com.jniwrapper.win32.FunctionName;
import com.jniwrapper.win32.IntPtr;
import com.jniwrapper.win32.Msg;
import com.jniwrapper.win32.process.Process;
import com.jniwrapper.win32.ui.User32;
import com.jniwrapper.win32.ui.Wnd;
 
/**
 * This example demonstrates how to wrap SetDlgItemText, GetDlgItemText and SendMessage API functions.
 *
 * @author Serge Piletsky
 */
public class WinInteraction {
 
    public static final FunctionName FUNCTION_SetDlgItemText = new FunctionName("SetDlgItemText");
    public static final FunctionName FUNCTION_GetDlgItemText = new FunctionName("GetDlgItemText");
    public static final FunctionName FUNCTION_SendMessage = new FunctionName("SendMessage");
    
    private static final String LOGIN_INFO = "LogInInfo";
    private static  final String DB_SERVER = "dbserver";	//数据库服务器地址
    private static final String ACCOUNT = "accout";		//数据库或者帐套
    private static final  String O_CODE = "ocode";		//组织
    private static final  String LOG_ID = "logid";
    private static final  String PWD = "pwd";
    private static final  String LANGUAGE = "language";
    private static final  String HID_MAINFORM = "hidmainform";
    private static final  String OTHER_PARAM = "otherparam";
    private static final  String FUNCTION_URL = "funtionurl";
    private static final String SEP_Str = "$@$";
    private static final int MSG_ID = 1036;//打开i6主框架 功能菜单的消息号
    
    private String loginInfo ;
    
    //读取netcall服务端的 该应用程序 的配置信息，此信息为所有用户共享的信息
    private String appAddressOnServer = AppSysRes.getPropertyOnServer(AppSysRes.APP_SERVER_URL);
    private String dbServerOnServer = AppSysRes.getPropertyOnServer(AppSysRes.APP_DBSERVER);
    private String dbServerAccountOnServer = AppSysRes.getPropertyOnServer(AppSysRes.APP_DBSERVER_ACCOUNT);
    
    //默认组织，此字段用户的对应私有信息
    private String userDaultOcodeOnServer = AppSysRes.getPropertyOnServer(AppSysRes.APP_USER_DEFAULT_OCODE);
    
    private String appServerAddress ;
//    private String appServerAddress = tempAddressOnServer.indexOf("/i6Service")==-1?tempAddressOnServer:tempAddressOnServer.substring(0, tempAddressOnServer.indexOf("/i6Service"));
    
    private String dbserver = dbServerOnServer;
    private String accout = dbServerAccountOnServer;
    private String ocode = userDaultOcodeOnServer;
    private String logid = SparkManager.getSessionManager().getUsername();
//    private String logid = "01";
    private String pwd = SparkManager.getSessionManager().getPassword();
//    private String pwd = "";
    private String language = AppSysRes.getString(AppSysRes.APP_LANGUAGE);
    private String hidmainform = AppSysRes.getString(AppSysRes.APP_HID_MAINFORM);
    private String otherparam = AppSysRes.getString(AppSysRes.APP_OTHER_PARAM);
    private String functionURL = AppSysRes.getString(AppSysRes.APP_FUNCTION_URL);
    
    private SettingPreference settingPreference = IntegrationManager.getSettingPreference();
    
    public WinInteraction(){
    	
    }
    
    /**
     * 
     * 登入到默认的一个应用系统地址
     * 
     * 该系统地址在该插件的 属性配置文件中设置
     * 拼接loginInfo字符串，
     *	
     * 
     */
    public void buildLoginInfo(){
    	String functionURL = AppSysRes.getString(AppSysRes.APP_FUNCTION_URL);
    	String tempLoginInfo = DB_SERVER + "=" + dbserver + SEP_Str + ACCOUNT + "=" + accout + SEP_Str 
    	+ O_CODE + "=" + ocode + SEP_Str + LOG_ID + "=" + logid + SEP_Str 
    	+ PWD + "=" + pwd + SEP_Str + LANGUAGE + "=" + language + SEP_Str 
    	+ HID_MAINFORM + "=" + hidmainform + SEP_Str 
    	+ OTHER_PARAM + "=" + otherparam + SEP_Str
    	+ FUNCTION_URL + "=";
    	
    	loginInfo=StringUtil.EncodeStringNG(tempLoginInfo, 1024); 

    }
    
    /**
     * 拼接loginInfo字符串
     * @param 
     */
    public void buildLoginInfo(String functionURL){
    	if(StringUtil.isEmpty(functionURL)){
    		buildLoginInfo();
    		return;
    	}
    	String tempLoginInfo = DB_SERVER + "=" + dbserver + SEP_Str + ACCOUNT + "=" + accout + SEP_Str 
				+ O_CODE + "=" + ocode + SEP_Str + LOG_ID + "=" + logid + SEP_Str 
				+ PWD + "=" + pwd + SEP_Str + LANGUAGE + "=" + language + SEP_Str 
				+ HID_MAINFORM + "=" + hidmainform + SEP_Str 
				+ OTHER_PARAM + "=" + otherparam + SEP_Str
				+ FUNCTION_URL + "=" + functionURL;
    	
    	loginInfo=StringUtil.EncodeStringNG(tempLoginInfo, 1024); 
    	loginInfo = StringUtils.replace(loginInfo, "&","$$**");
    }
    
    
    /**
     * 根据系统功能地址打开应用系统
     *  
     *  如果functionURL为空,而且应用系统已经打开，则不做任何处理 
     * 
     * @param functionURL  
     */
    
    public void loginAppSys(final String functionURL){
    	
//    	setFunctionURL(functionURL);
		buildLoginInfo(functionURL);
		try {
			final Wnd appSysWindow = Wnd.findWindowByName("NGWinFormAntenna");
			if (appSysWindow.getThreadId() != 0) {
				if (!StringUtil.isEmpty(functionURL)) {
					SwingUtilities.invokeLater(new Runnable() {
	                    public void run() {
	                    	sendFunctionURL(appSysWindow, functionURL);
	                    }
	                });
				}
			} else {
				if(StringUtil.isEmpty(getAppServerAddress())||StringUtil.isEmpty(dbserver)||StringUtil.isEmpty(accout)){
					 JOptionPane.showMessageDialog(SparkManager.getMainWindow(),"服务端没有配置单点登入信息,先通知管理员配置！");
					 return ;
		    	}else if(StringUtil.isEmpty(ocode)){
		    		JOptionPane.showMessageDialog(SparkManager.getMainWindow(),"请先设置默认的组织");
		    		return;
		    	}
				BrowserLauncher.openURL(getAppServerAddress()+"/PCS/i6.Presentation.MainFrame/login.aspx?"+LOGIN_INFO+"="+ loginInfo);
			}
		} catch (IOException e) {
			Log.error(e.getMessage());
		}
    }
    
    private String getAppServerAddress(){
    	return settingPreference.getPreferences().getSelectedLoginURL();
    }
    
    /**
     * 向指定的窗口，发送functionURL字符串
     * 
     * @param appSysWindow
     * @param functionURL
     */
    public void sendFunctionURL(Wnd appSysWindow,String functionURL){
    	// send WM_SETTEXT message to change the caption of Notepad window
    	char[] chars = functionURL.toCharArray();
    	for (int i = 0; i < chars.length; i++) {
			char c = chars[i];
			sendMessage(appSysWindow, MSG_ID, null, new Char(c));	
		}
    	sendMessage(appSysWindow, MSG_ID, null, new Int(0));
    }
    
    
    public void setFunctionURL(String functionURL){
    	this.functionURL = functionURL;
    }
    
    public String getFunctionURL(){
    	return functionURL;
    }
    
    /**
     * Sends a message to the specified window.
     *
     * @param wnd    window handle
     * @param msg    message
     * @param wParam WPARAM
     * @param lParam LPARAM
     * @return the return value meaning depends on the message.
     */
    public static long sendMessage(Wnd wnd, int msg, Parameter wParam, Parameter lParam) {
        Function sendMessage = User32.getInstance().getFunction(FUNCTION_SendMessage.toString());
        IntPtr result = new IntPtr();
        sendMessage.invoke(result,
                wnd,
                new UInt(msg),
                wParam != null ? wParam : new IntPtr(),
                lParam != null ? lParam : new IntPtr());
        return result.getValue();
    }
 
    /**
     * Sets the title or text of a control in a dialog box.
     *
     * @param wnd       Handle to the dialog box that contains the control
     * @param idDlgItem Specifies the control with a title or text to be set
     * @param string    String that contains the text to be copied to the control
     * @return If the function succeeds, the return value is true
     */
    public static boolean setDlgItemText(Wnd wnd, int idDlgItem, String string) {
        Function sendMessage = User32.getInstance().getFunction(FUNCTION_SetDlgItemText.toString());
        Bool result = new Bool();
        sendMessage.invoke(result,
                wnd,
                new Int(idDlgItem),
                new Pointer(new Str(string)));
        return result.getValue();
    }
 
    /**
     * Returns the title or text associated with a control in a dialog box.
     *
     * @param wnd       Handle to the dialog box that contains the control
     * @param idDlgItem Specifies the control with a title or text to be set
     * @return return value is true
     */
    public static String getDlgItemText(Wnd wnd, int idDlgItem) {
        Function sendMessage = User32.getInstance().getFunction(FUNCTION_GetDlgItemText.toString());
        final int maxCount = 512;
        Bool result = new Bool();
        Str resultString = new Str(maxCount);
        sendMessage.invoke(result,
                wnd,
                new Int(idDlgItem),
                new Pointer(resultString),
                new Int(maxCount));
        return resultString.getValue();
    }
 
    public static void main(String[] args) throws Exception {
        // start Notepad application and wait 2 seconds
//        Process notepadProcess = new Process("notepad");
        Thread.sleep(2000);
 
        String loginInfo = "dbserver=weizj$@$accout=0002$@$ocode=001$@$logid=01$@$language=zh-cn$@$hidmainform=0$@$otherparam=$@$funtionurl=exe:[i6p][INTFI]DC:11:10201";
        
        String functionURL = "exe:[i6p][INTFI]DC:11:10201";
        char[] chars = functionURL.toCharArray();
        
        // find Notepad window
//        Wnd notepadWindow = Wnd.findWindowByName("无标题 - 记事本");
        Wnd notepadWindow = Wnd.findWindowByName("NGWinFormAntenna");
        if(notepadWindow.getThreadId()!=0){
        	// send WM_SETTEXT message to change the caption of Notepad window
        	for (int i = 0; i < chars.length; i++) {
				char c = chars[i];
				sendMessage(notepadWindow, MSG_ID, null, new Char(c));	
			}
        	sendMessage(notepadWindow, MSG_ID, null, new Int(0));	
//            sendMessage(notepadWindow, 1023+4, null, new Char('a'));
            
        }else {
        	BrowserLauncher.openURL("http://10.0.13.30/i6/PCS/i6.Presentation.MainFrame/login.aspx?LogInInfo="+loginInfo);
        }
        
 
        // send WM_SETTEXT message to change the caption of Notepad window
//        sendMessage(notepadWindow, Msg.WM_SETTEXT, null, new Pointer(new Str("Hello, World!")));
        
//        Thread.sleep(2000);
 
        // send WM_CLOSE message to close the Notepad window
        sendMessage(notepadWindow, Msg.WM_CLOSE, null, null);
 
//        notepadProcess.waitFor();
        System.out.println("Done.");
        
//        Str string = new Str("String value");
//        Pointer stringPtr = new Pointer(string);
//     
//        Pointer.Void stringHandle = new Pointer.Void();
//        stringPtr.castTo(stringHandle);
//     
//        long lParam = stringHandle.getValue();
//        notepadWindow.sendMessageEx(Msg.WM_SETTEXT, 1, lParam);

    }
}

